package m

import (
	"github.com/globalsign/mgo/bson"
	log "github.com/sirupsen/logrus"

	"GameServer/Game/cache"
	"GameServer/Game/dbmodule"
	"GameServer/Game/errors"
)

// 公会红包
type UnionRedPacket struct {
	BaseM
	Uid           bson.ObjectId   `bson:"_id" json:"_id"`                     // 用户uid
	SendRedPacket []*ChatMsg      `bson:"sendRedPacket" json:"sendRedPacket"` // 玩家发送的红包
	RecvRedPacket []*GetRedPacket `bson:"recvRedPacket" json:"recvRedPacket"` // 玩家领过的红包
}

// 领取红包信息
type GetRedPacket struct {
	Mid      string `bson:"mid" json:"mid"`           // 聊天消息id
	RecvTime int64  `bson:"recvTime" json:"recvTime"` // 领取时间
}

func NewUnionRedPacket() cache.EntryI {
	return &UnionRedPacket{
		SendRedPacket: make([]*ChatMsg, 0),
		RecvRedPacket: make([]*GetRedPacket, 0),
	}
}

func (this *UnionRedPacket) Save() (err error) {
	err = dbmodule.MgoDB.GameDB.Upsert("UnionRedPacket", bson.M{"_id": this.Uid}, this)
	return
}

func (this *UnionRedPacket) Load(key interface{}) (err error) {
	switch key.(type) {
	case string:
		if key.(string) == "" {
			return errors.New("无效的key load, key empty")
		}
		this.Uid = bson.ObjectIdHex(key.(string))
	case bson.ObjectId:
		this.Uid = key.(bson.ObjectId)
	default:
		log.WithFields(log.Fields{
			"method": "UnionRedPacket_Load",
			"data":   key,
		}).Error("无效的key load")
		return errors.New("无效的key load")
	}
	return this.LoadData()
}

func (this *UnionRedPacket) LoadData() (err error) {
	err = dbmodule.MgoDB.GameDB.FindOne("UnionRedPacket", bson.M{"_id": this.Uid}, nil, &this)
	if err != nil {
		if err.Error() == "not found" {
			return nil
		}
		return
	}
	return
}

func (this *UnionRedPacket) Update(val *UnionRedPacket) {
	Cache.Put("UnionRedPacket", val.Uid.Hex(), val)
	val.UpdateData()
}

func GetUnionRedPacket(uid string) (r *UnionRedPacket) {
	v, _ := Cache.Get("UnionRedPacket", uid)
	r = v.(*UnionRedPacket)
	return
}

// 记录玩家发放的红包
func (this *UnionRedPacket) AddRedPacket(msgChat *ChatMsg) {
	defer this.Update(this)
	if len(this.SendRedPacket) > 500 {
		this.SendRedPacket = append(this.SendRedPacket[1:], msgChat)
		return
	}
	this.SendRedPacket = append(this.SendRedPacket, msgChat)
}

// 判断红包领过
func (this *UnionRedPacket) IsRecv(mid string) bool {
	for _, item := range this.RecvRedPacket {
		if item.Mid == mid {
			// 该红包领过
			return true
		}
	}
	// 该红包未领过
	return false
}

// 获取发送的红包
func (this *UnionRedPacket) GetSendRedPacket(mid string) (msgChat *ChatMsg, ok bool) {
	for _, item := range this.SendRedPacket {
		if item.Mid == mid {
			msgChat = item
			ok = true
			return
		}
	}
	return
}

// 记录领取的红包
func (this *UnionRedPacket) AddRecvRedPacket(recv *GetRedPacket) {
	defer this.Update(this)
	if len(this.RecvRedPacket) > 500 {
		this.RecvRedPacket = append(this.RecvRedPacket[1:], recv)
		return
	}
	this.RecvRedPacket = append(this.RecvRedPacket, recv)
}

// 清理玩家的红包信息
func (this *UnionRedPacket) Clear() {
	unionRedPacket := &UnionRedPacket{
		Uid: this.Uid,
	}
	this.Update(unionRedPacket)
}
